package com.xiaoyu.lanling.feature.setting.util

import android.annotation.TargetApi
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import com.xiaoyu.base.app.App
import com.xiaoyu.base.app.AppContext
import com.xiaoyu.base.utils.MMKVUtil
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.data.NotificationData
import com.xiaoyu.lanling.feature.setting.service.NotificationService

class NotificationUtil {

    private var serviceIntent: Intent? = null

    companion object {
        val instance by lazy { NotificationUtil() }
    }

    fun showNotificationIfNeed() {
        val enable = MMKVUtil.get()?.getBoolean(Constant.MMKVKey.KEY_NOTIFICATION_SERVICE_ENABLE, false)
                ?: false
        if (!enable) {
            return
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startService()
        }
    }

    fun dismissNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            stopCallingService()
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun startService() {
        serviceIntent = createServiceIntent()
        AppContext.getContext().startForegroundService(serviceIntent)
    }

    @TargetApi(Build.VERSION_CODES.O)
    private fun stopCallingService() {
        if (serviceIntent == null) {
            return
        }
        AppContext.getContext().stopService(serviceIntent)
        serviceIntent = null
    }

    private fun createServiceIntent(): Intent? {
        return Intent(AppContext.getContext(), NotificationService::class.java)
    }

    fun createIntent(context: Context): Intent? {
        val activity = App.getInstance().topActivity ?: return null

        val intent = Intent(context, activity::class.java)
        intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED or Intent.FLAG_ACTIVITY_NEW_TASK)
        return intent
    }

    @RequiresApi(Build.VERSION_CODES.N)
    fun buildNotification(title: CharSequence?, text: CharSequence?, pendingIntent: PendingIntent?): Notification {
        return NotificationCompat.Builder(AppContext.getContext(), NotificationData.ChannelId.NOTIFICATION_SERVICE)
                .setContentTitle(title)
                .setContentText(text)
                .setContentIntent(pendingIntent)
                .setTicker(text)
                .setWhen(System.currentTimeMillis())
                .setDefaults(Notification.DEFAULT_ALL)
                .setSmallIcon(R.drawable.mipush_small_notification)
                .setPriority(NotificationManager.IMPORTANCE_LOW)
                .setAutoCancel(true)
                .build()
    }
}